package com.wny.activities;

import java.io.IOException;

import com.wny.R;
import com.wny.backend.SocketsClient;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
 
public class SignUpActivity extends Activity {
	Button createAccBtn;
	OnClickListener createListener = null;
	SocketsClient socket;
	int uid = -1;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_account);
		createListener = new OnClickListener() {
			public void onClick(View v) {
				Intent signIntent = new Intent(SignUpActivity.this,
						MainMenuActivity.class);
				setTitle("Sign Up");
				if(tryCreateAccount(v) == true){
					startActivity(signIntent);
				}		
			}
		};
		createAccBtn = (Button) findViewById(R.id.createAccountButton);
		createAccBtn.setOnClickListener(createListener);
	}

	public boolean tryCreateAccount(View V){
		boolean isValid = true;
		String username = ((EditText) findViewById(R.id.username)).getText()
				.toString();
		String password = ((EditText) findViewById(R.id.password)).getText()
				.toString();
		String confirm_password = ((EditText) findViewById(R.id.passwordConfirm))
				.getText().toString();
		String email = null;
		String sex = null;

		boolean password_match;
		password_match = Password_Match_Check(password, confirm_password);
		// if passwords to not match let user know and return (exit function)
		if (password_match == false) {
			isValid = false;
			return isValid;
		}
		// If skip email is checked, do not get email from textbox
		if (!((CheckBox) findViewById(R.id.emailCheckbox)).isChecked()) {
			email = ((EditText) findViewById(R.id.emailBox)).getText()
					.toString();
			// communicate.send(null);
		}
		// get user's sex
		if (((RadioButton) findViewById(R.id.male)).isChecked())
			sex = "m";
		else
			sex = "f";

		StringBuilder toSend = new StringBuilder("add=user&name=")
				.append(username).append("&pwd=").append(password)
				.append("&email=").append(email).append("&sex=" + sex + "\n");
		try {
			// if 1, then data retrieved successfully. Else there was a problem
			// making the account
			char[] v = socket.sendData(toSend.toString().getBytes());
			if (v[0] == '1') {
				toSend = new StringBuilder("add=privacy&uid=" + uid
						+ "&private=1\n");
				socket.sendData(toSend.toString().getBytes());
				// setContentView(R.layout.loggedinview);
				setUID(username);
				displayWithToast("Sucessfully logged in", 4000);
				isValid = true;
			}
			else {
				
				if(username.length()>30){
					displayWithToast("Error-Username is longer than 30 characters",4000);
					
				}
				displayWithToast("Problem creating account ):", 4000);
				isValid = false;
			}

		} catch (Exception e) {
			displayWithToast("Error in network communication; action aborted",
					4000);
		}
		return isValid;

	}

	private void setUID(String username) {
		try {
			char[] uid = socket.sendData(("getid=user&name=" + username + "\n")
					.getBytes());
			this.uid = Integer.valueOf(String.valueOf(uid).split("/")[0]);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public boolean Password_Match_Check(String password, String confirm_password) {
		if (!password.equals(confirm_password)) {
			displayWithToast("Error-Password Mismatch", 5000);
			return false;
		}
		return true;
	}
	public void greyEmail(View V)
	{
		CheckBox emailCheck = ((CheckBox)findViewById(R.id.emailCheckbox));
		if(!emailCheck.isChecked())
			((EditText)findViewById(R.id.emailBox)).setEnabled(true);
		else
			((EditText)findViewById(R.id.emailBox)).setEnabled(false);					
	}
	// a wrapper function for the Toast class. Used to show messages onscreen
	private void displayWithToast(String toShow, int duration) {
		Toast temp = Toast.makeText(this, toShow, duration);
		temp.setGravity(Gravity.CENTER, 0, 0);
		temp.show();
	}

	// the Restart,onResume,Pause, and Stop functions deals with loopback with
	// Android emulator
	// loopback for Anroid emulator is 10.0.2.2 (not 127.0.0.1!)
	protected void onStart() {
		super.onStart();
		socket = SocketsClient.getSocket();
	}

	protected void onResume() {
		super.onResume();
		socket = SocketsClient.getSocket();
	}

	protected void onPause() {
		super.onPause();
	}

	protected void onStop() {
		super.onStop();
	}
}
